package com.bckj.fastboot.iot.data.mongo.repository;

import com.bckj.fastboot.core.extra.mongo.AbstractMongoRepository;
import com.bckj.fastboot.core.extra.mongo.MongoOps;
import com.bckj.fastboot.core.lang.model.PageResult;
import com.bckj.fastboot.iot.common.dto.query.IotAlarmDataQuery;
import com.bckj.fastboot.iot.common.dto.request.IotAlarmDataRequest;
import com.bckj.fastboot.iot.common.dto.response.IotAlarmDataResponse;
import com.bckj.fastboot.iot.common.repository.IotAlarmDataRepository;
import com.bckj.fastboot.iot.data.mongo.convert.IotAlarmDataConvert;
import com.bckj.fastboot.iot.data.mongo.entity.IotAlarmData;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * IotAlarmDataRepositoryImpl
 *
 * @author wfc
 **/
@Repository
public class IotAlarmDataRepositoryImpl
    extends AbstractMongoRepository<IotAlarmData, Long>
    implements IotAlarmDataRepository {

    private final IotAlarmDataConvert iotAlarmDataConvert;

    public IotAlarmDataRepositoryImpl(
            MongoOps mongoOps,
            IotAlarmDataConvert iotAlarmDataConvert) {
        super(mongoOps, IotAlarmData.class, "iot_alarm_data");
        this.iotAlarmDataConvert = iotAlarmDataConvert;
    }


    @Override
    public boolean save(IotAlarmDataRequest request) {
        var entity = iotAlarmDataConvert.toEntity(request);
        return save(entity);
    }

    @Override
    public boolean updateById(IotAlarmDataRequest request) {
        var entity = iotAlarmDataConvert.toEntity(request);
        return updateById(entity);
    }

    @Override
    public IotAlarmDataResponse details(Long id) {
        return findById(id, IotAlarmDataResponse.class);
    }

    @Override
    public IotAlarmDataResponse findLatestOne(IotAlarmDataQuery query) {
        return getMongoOps().findOne(buildQuery(query), IotAlarmDataResponse.class, getCollectionName());
    }

    @Override
    public List<IotAlarmDataResponse> findList(IotAlarmDataQuery query) {
        return find(buildQuery(query), IotAlarmDataResponse.class);
    }

    @Override
    public PageResult<IotAlarmDataResponse> page(Pageable page, IotAlarmDataQuery query) {
        return page(page, buildQuery(query), IotAlarmDataResponse.class);
    }

    private Query buildQuery(IotAlarmDataQuery query) {
        Criteria criteria = Criteria.where("devCode").is(query.getDevCode());
        return Query.query(criteria);
    }

}
